package net.xdclass.service.impl;

import net.xdclass.service.GoogleSafeBrowsingService;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.util.concurrent.CompletableFuture;

@Service
public class GoogleSafeBrowsingServiceImpl implements GoogleSafeBrowsingService {

    private static final String API_KEY = "your_google_safe_browsing_api_key";
    private static final String API_URL = "https://safebrowsing.googleapis.com/v4/threatMatches:find";

    @Override
    public CompletableFuture<Boolean> detect(String url) {
        return CompletableFuture.supplyAsync(() -> {
            RestTemplate restTemplate = new RestTemplate();
            try {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);

                StringBuilder requestBody = new StringBuilder();
                requestBody.append("{\"client\":{\"clientId\":\"your_client_id\",\"clientVersion\":\"1.0\"},\"threatInfo\":{\"threatTypes\":[\"MALWARE\",\"SOCIAL_ENGINEERING\"],\"platformTypes\":[\"ANY_PLATFORM\"],\"threatEntryTypes\":[\"URL\"],\"threatEntries\":[{\"url\":\"");
                requestBody.append(url);
                requestBody.append("\"}]}}");

                HttpEntity<String> request = new HttpEntity<>(requestBody.toString(), headers);
                String fullUrl = API_URL + "?key=" + API_KEY;

                ResponseEntity<String> response = restTemplate.postForEntity(fullUrl, request, String.class);
                return response.getBody() != null && response.getBody().contains("matches");
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        });
    }
}
